package com.zhiwang.planet.mvvm.viewmodel.my

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider
import com.zhiwang.planet.di.ActivityScope
import com.zhiwang.planet.mvvm.model.RestApi
import me.tatarka.bindingcollectionadapter2.ItemBinding
import com.zhiwang.planet.BR
import com.zhiwang.planet.R
import com.zhiwang.planet.event.AvatarChangeEvent
import com.zhiwang.planet.mvvm.model.entity.User
import com.zhiwang.planet.mvvm.model.entity.UserDao
import com.zhiwang.planet.ui.my.BindPayPasswordActivity
import com.zhiwang.planet.util.*
import com.zhiwang.planet.widget.InputPromotionDialog
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.hint_dialog.view.*
import org.greenrobot.eventbus.EventBus
import javax.inject.Inject

data class ExChangeItemViewModel(var type: String,
                                 var price: String,
                                 var value: String,
                                 var buff: String,
                                 var icon: String,
                                 var exChangeViewModel: ExChangeViewModel) {

    fun onExChange() {
        exChangeViewModel.exchange(type)
    }
}


@ActivityScope
class ExChangeViewModel @Inject constructor(var restApi: RestApi, var activity: AppCompatActivity, var userDao: UserDao) : ViewModel() {


    val itemBinding = ItemBinding.of<ExChangeItemViewModel>(BR.exchangeVm, R.layout.item_bean_exchange)

    val items = MutableLiveData<List<ExChangeItemViewModel>>()

    val diamond = MutableLiveData<String>()

    val bean = MutableLiveData<String>()

    @SuppressLint("CheckResult")
    fun start() {

        loadUerInfo()

        restApi.getExchangeList(Store.EXCHANGE_LIST_URL)
                .androidSchedule()
                .responseFunc()
                .subscribe({
                    items.value = it.conf.map { ExChangeItemViewModel(it.type, it.price, it.value, it.buffer, it.iconUrl, this) }
                }, {
                    Toaster.message(it.message ?: "")
                })
    }

    private fun loadUerInfo() {
//        restApi.getUserInfoEx()
//                .arrange(Consumer {
//                    diamond.value = String.format("%,d", it.diamond.toInt())
//                    bean.value = String.format("%,d", it.bean.toInt())
//                }, Consumer { }
//                        , Action { })
    }

    fun exchange(type: String) {

//        restApi.checkExchangeEnable()
//                .androidSchedule()
//                .autoDispose(scopeProvider = AndroidLifecycleScopeProvider.from(activity))
//                .subscribe({
//                    if (it.errCode == 1) {
//                        showHintDialog(it.errMsg)
//                    } else {
//
//                        doExchange(type)
//                    }
//
//
//                }, {
//
//                }, {
////
//                })

        doExchange(type)

    }

    private fun doExchange(type: String) {
        val user: User? =null

        if (user?.bindInfo?.hasSetPaypassword == false) {


            AlertDialog.Builder(activity)
                    .setTitle("绑定交易密码")
                    .setMessage("还未设置交易密码")
                    .setNegativeButton("取消") { i, k ->
                        i.dismiss()

                    }
                    .setPositiveButton("设置交易密码") { i, k ->
                        activity.quickStartActivity(BindPayPasswordActivity::class.java)
                    }
                    .create()
                    .show()

            return

        }


        /**
         * is_xq 固定死为1，  gold_num就是conf接口里返回的goods_type值， pay_passwd交易密码
         */

        InputPromotionDialog.create(activity, object : InputPromotionDialog.Companion.OnPromoteListener {
            override fun onPromote(pwd: String) {
                val params = hashMapOf<String, String>()
                params["is_xq"] = "1"
                params["gold_num"] = type
                params["pay_passwd"] = pwd
                restApi.exChangeBean(Store.EXCHANGE_BEAN_URL, params)
                        .arrangeComplete(Action {

                            loadUerInfo()
                            EventBus.getDefault().post(AvatarChangeEvent())
                            Toaster.message("申请兑换成功")
                        }) {

                            Toaster.message(it.message ?: "")
                        }
            }

        })
    }

    private fun showHintDialog(type: String) {

        val root = LayoutInflater.from(activity).inflate(R.layout.hint_dialog, null)
        root.msg.text = type
        val create = AlertDialog.Builder(activity)
                .setView(root)
                .create()

        root.positive_btn.setOnClickListener {
            activity.suicideAfterTransition()
        }

        root.negative_btn.setOnClickListener {

        }

        create.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        create.show()
    }
}